import { loadResources } from './tool'
import { defHttp } from '../http'

type CFun = null | undefined | ((type: ShareType) => void);

interface Config {
  title: string
  desc: string
  image: string
  link?: string
}

export enum ShareType { HH, WX, WXTime, QQ, QQZone, Weibo}

/**
 * @description 获取wx签名认证
 * @param { string } url 签名认证 - 请求地址
 * @param { object } data 请求参数
 * @return { promise } http请求对象
 */
function getSign(url: string, data: object) {
  return defHttp.request({
    url,
    method: 'post',
    data
  }, {
    isNeedToken: false,
    isTransformResponse: false
  })
}

/**
 * @description 初始化wx sdk，返回Promise对象
 * @param { WxConfig } config
 * config.shareInfo:{
 *    title: data.title,
 *    desc: data.desc,
 *    link: data.link,
 *    imgUrl: data.imgUrl,
 *    type: 'link',
 *    dataUrl: '',
 *    success: data.success,
 *    cancel: data.cancel
 * }
 */
const wxShareInit = (config: any) => {
  const { wx } = window
  const { debug = false, url, signParams = {}, shareInfo, jsApiList = [], apiAction, handleSignResponse } = config
  // 默认分享api
  const shareApi = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo']
  return new Promise((resolve, reject) => {
    getSign(url, signParams).then(result => {
      const res = handleSignResponse(result)
      /**
       * @description 处理返回值 res (object | undefind)
       * ｛
       *    appId: '', // 必填，公众号的唯一标识
       *    timestamp: , // 必填，生成签名的时间戳
       *    nonceStr: '', // 必填，生成签名的随机串
       *    signature: '',// 必填，签名，见附录1
       *  ｝
       */
      if (!res) {
        return reject(new Error('获取签名数据失败'))
      }
      wx.config({
        debug,
        ...res,
        jsApiList: [...new Set([...shareApi, ...jsApiList])] // 必填，需要使用的JS接口列表
      })
      wx.ready(() => {
        if (shareInfo) {
          // 注册js分享api  (1、2、3、5)参考share.tsx的枚举ShareType
          const { title, desc, link, imgUrl, type, dataUrl, success, cancel } = shareInfo
          wx.onMenuShareAppMessage({
            title,
            desc,
            link,
            imgUrl,
            type,
            dataUrl,
            success: () => success && success(ShareType.WX),
            cancel: cancel
          })
          wx.onMenuShareTimeline({
            title: desc,
            link: link,
            imgUrl: imgUrl,
            success: () => success && success(ShareType.WXTime),
            cancel: cancel
          })
          wx.onMenuShareQQ({ ...shareInfo, success: () => success && success(ShareType.QQ) })
          wx.onMenuShareWeibo({ ...shareInfo, success: () => success && success(ShareType.Weibo) })
        }
        // 注册jsApiList表定义的api方法
        apiAction && apiAction(wx)
        resolve(true)
      })
      wx.error((error: Error) => {
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        reject(error)
      })
    }).catch(error => {
      reject(error)
    })
  })
}

/*
* 分享
* */
export const setupShare = (config: Config, success?: CFun, cancel?: CFun) => {
  const { origin, pathname } = window.location
  const link = config.link || origin + pathname
  const isHeyHey = window.isHeyHeyTalk && window.isHeyHeyTalk()
  if (isHeyHey) {
    const { HeyheyBridge } = window
    HeyheyBridge.setTopBarShare({
      config: { link, ...config },
      wxtimeline: true,
      wxmessage: true,
      qq: true,
      qzone: true
    }, (e: any) => {
      console.log(e, 'heyhey setTopBarShare')
    })
  } else {
    const { image, ...rest } = config
    const shareInfo = {
      link,
      imgUrl: image,
      ...rest,
      type: 'link',
      success: (data: any) => {
        console.log(data, 'setupShareSuccess')
        if (success) {
          success(data)
        }
      },
      cancel: (data: any) => {
        console.log(data)
        if (cancel) {
          cancel(data)
        }
      }
    }
    loadResources('//res.wx.qq.com/open/js/jweixin-1.2.0.js', () => {
      let { baseUrl } = process.env
      if(process.env.APP_ENV === 'production'){
        baseUrl = window.location.origin
      }
      wxShareInit({
        url: `${baseUrl}/Wchat/sign5235`,
        signParams: { url: link },
        shareInfo,
        handleSignResponse(res: any) {
          if (res.status === 200) {
            return res.data
          }
        }
      }).catch((e: any) => {
        console.log(e)
      })
    })
  }
}


/**
 * @description 根据static path 获取 icon url
 * @param staticPath ./abc/efddfd/a.png
 */
export const getShareIconUrl = (staticPath: string) =>{
  return `${window.location.origin}${window.location.pathname}${staticPath.substring(1)}`
}
